#include "GridPoistionerWidget.h"

void RGridPoistionerWidget::CalculatePresentPositionAndSize()
{
    bChildrenArranged=false;
    Super::CalculatePresentPositionAndSize();
}

void RGridPoistionerWidget::CalculateChildrenPresentPositionAndSize()
{
    if(!bChildrenArranged)
    {
        ArrangeChildren();
    }
    
    Super::CalculateChildrenPresentPositionAndSize();

}

float RGridPoistionerWidget::CalculateContentWidth()
{
    if(!bChildrenArranged)
    {
        ArrangeChildren();
    }
    return ContentSize.X;
}

float RGridPoistionerWidget::CalculateContentHeight()
{
    if(!bChildrenArranged)
    {
        ArrangeChildren();
    }
    return ContentSize.Y;
}

void RGridPoistionerWidget::ArrangeChildren()
{
    assert(bChildrenArranged==false);
    bChildrenArranged=true;


    auto _ColumnNum=ColumnNum.Get();
    if(_ColumnNum>0)
    {   
        TVector<float> ColumnSize;
        ColumnSize.Resize(_ColumnNum);

        TVector<float> RowSize;
        RowSize.Resize(SubWidgets.Num()%_ColumnNum==0? SubWidgets.Num()/_ColumnNum : (SubWidgets.Num()/_ColumnNum+1)  );

        for(int32_t Index=0; Index<SubWidgets.Num();Index++)
        {
            int32_t Row=Index/_ColumnNum;
            int32_t Column=Index-Row*_ColumnNum;

            //const SVec2& Size=SubWidgets[Index]->Size;
            float Width=SubWidgets[Index]->Width.Get();
            float Height=SubWidgets[Index]->Height.Get();
            if(Width>ColumnSize[Column])
            {
                ColumnSize[Column]=Width;
            }

            if(Height>RowSize[Row])
            {
                RowSize[Row]=Height;
            }
        }

        //calculate the content size
        ContentSize.X=(ColumnSize.Num()-1)*ColumnSpacing;
        for(int32_t Index=0; Index<ColumnSize.Num();Index++)
        {
            ContentSize.X+=ColumnSize[Index];
        }

        ContentSize.Y=(RowSize.Num()-1)*RowSpacing;
        for(int32_t Index=0; Index<RowSize.Num();Index++)
        {
            ContentSize.Y+=RowSize[Index];
        }



        SVec2 Position(0,0);
        for(int32_t Index=0; Index<SubWidgets.Num();Index++)
        {
            int32_t Row=Index/_ColumnNum;
            int32_t Column=Index-Row*_ColumnNum;

            if(Column==0)
            {
                Position.X=0;

                if(Row>0)
                {
                    //meet a  new line 
                    Position.Y+=RowSize[Row-1]+RowSpacing;
                }

            }
            else
            {
                Position.X+=ColumnSize[Column-1] + ColumnSpacing;
            }


            SubWidgets[Index]->X=Position.X;
            SubWidgets[Index]->Y=Position.Y;
            
            SubWidgets[Index]->CalculatePresentPositionAndSize();
        }

    }

    
    OnChildrenArranged.ExecuteIfBound();
}